package com.example.managerment.util;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.Data;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

//jwt:
//  secret: Audit2022
//  validity: 180000
@Component
@Data
public class JwtUtil {
    static final String USER_NAME = "username";//用户id
    static final String TOKEN_SUB = "uuid";//私有编号
    private String secret = "Audit2022";//盐

    private Long validity = 180000L;//有效期

    /**
     * 生成token
     * @param username
     * @return
     */
    public String generateToken(String username){
        //header
        Map<String,Object> header = new HashMap<>();
        header.put("alg","HS256");
        header.put("typ","JWT");

        //payload: 签发时间
        long created = System.currentTimeMillis();
        Date issued = new Date(created);

        //payload: 过期时间
        long expires = created + validity;
        Date expiration = new Date(expires);

        //私有声明
        Map<String,Object> cliams = new HashMap<>();
        cliams.put(TOKEN_SUB, UUID.randomUUID());
        cliams.put(USER_NAME, username);
        return Jwts.builder()
                .setHeader(header)
                .setClaims(cliams)
                .setIssuedAt(issued)
                .setExpiration(expiration)
                .signWith(SignatureAlgorithm.HS256,secret)
                .compact();



    }

    /**
     * 解析token
     * @param token
     * @return
     */
   public Claims parseToken(String token){
       /**
        * claim是一条身份信息，token中包含了多个claim
        * token中claim由签发者发布
        */
        Claims claims = Jwts.parser()
                .setSigningKey(secret)//识别签名者
                .parseClaimsJws(token)
                .getBody();
        return claims;
   }

    /**
     * 判断token身是否有效
     * @param token
     * @return
     */
   public boolean isExpires(String token){
       /**
        * 如果token不为空
        * 解析token，如果token过期，会产生异常
        */
       if(token == null){
           return true;
       }
       try{
           Claims claims = parseToken(token);
       } catch (Exception e) {
           return true;
       }
       return false;
   }

    /**
     * 获取toekn用户id
     * @param token
     * @return
     */
   public String getUserName(String token){
       //从声明中获取用户
       Claims claims = parseToken(token);
       return (String) claims.get(USER_NAME);
   }

    /**
     * 验证token是否合法
     * @param accessToken
     * @param validityToken
     * @return
     */
   public boolean validityToken(String accessToken,String validityToken){
       if(validityToken !=null){
           if(accessToken.equals(validityToken)){
               return true;
           }
       }
       return false;
   }


}
